﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace FileSharing
{
    public class Log
    {
        private static Log singleton = null;

        private FileStream file;
        private TextWriter filewriter;
        private Main logwriter;

        private Log()
        {
            try
            {
                file = new FileStream("bimshare.log", FileMode.OpenOrCreate);

                filewriter = new StreamWriter(file);

                file.Seek(0, SeekOrigin.End);
            }
            catch (Exception e)
            {
                // TODO: Show message box!
            }
        }

        ~Log()
        {
            file.Close();
        }

        public static Log Instance()
        {
            if (singleton == null)
                singleton = new Log();

            return singleton;
        }

        public void RegisterOutput(Main mainform)
        {
            logwriter = mainform;
        }

        public void Print(String text)
        {
            filewriter.Write(text);
            filewriter.Flush();

            if (logwriter != null)
                logwriter.Text += text;
        }

        public void PrintLine(String text)
        {
            TimeSpan now = DateTime.Now.TimeOfDay;
            string nowString = now.Hours.ToString("00") + ":" + now.Minutes.ToString("00") + ":" + now.Seconds.ToString("00");

            filewriter.WriteLine(nowString + " - " + text);
            filewriter.Flush();

            if (logwriter != null)
                logwriter.WriteToLog(nowString + " - " + text + "\r\n");
        }
    }
}
